package controllers

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"

	"library/models"
)

// 获取所有借阅记录
func GetBorrows(c *gin.Context) {
	var borrows []models.Borrow
	DB.Preload("Book").Preload("User").Find(&borrows)
	c.HTML(http.StatusOK, "borrow_list.html", gin.H{"Borrows": borrows})
}

// 显示添加借阅记录页面
func ShowAddBorrowPage(c *gin.Context) {
	var books []models.Book
	var users []models.User
	DB.Find(&books)
	DB.Find(&users)
	c.HTML(http.StatusOK, "borrow_add.html", gin.H{"Books": books, "Users": users})
}

// 添加借阅记录提交
func AddBorrow(c *gin.Context) {
	bookID, _ := strconv.ParseUint(c.PostForm("book_id"), 10, 32)
	userID, _ := strconv.ParseUint(c.PostForm("user_id"), 10, 32)
	borrowDateStr := c.PostForm("borrow_date")
	borrowDate, _ := time.Parse("2006-01-02", borrowDateStr)

	borrow := models.Borrow{
		BookID:     uint(bookID),
		UserID:     uint(userID),
		BorrowDate: borrowDate,
	}
	DB.Create(&borrow)

	// 操作日志
	log := models.Log{Action: "添加借阅: BookID=" + strconv.FormatUint(bookID, 10) + ", UserID=" + strconv.FormatUint(userID, 10), Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/borrows")
}

// 归还图书（更新借阅记录）
func ReturnBorrow(c *gin.Context) {
	id := c.Param("id")
	var borrow models.Borrow
	DB.First(&borrow, id)
	now := time.Now()
	borrow.ReturnDate = &now
	DB.Save(&borrow)

	// 操作日志
	log := models.Log{Action: "归还借阅 ID: " + id, Timestamp: now}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/borrows")
}

// 删除借阅记录
func DeleteBorrow(c *gin.Context) {
	id := c.Param("id")
	var borrow models.Borrow
	DB.First(&borrow, id)
	DB.Delete(&borrow)

	// 操作日志
	log := models.Log{Action: "删除借阅记录 ID: " + id, Timestamp: time.Now()}
	DB.Create(&log)

	c.Redirect(http.StatusFound, "/borrows")
}
